from flask import render_template, redirect, url_for, flash, request
from . import bp

# 简单的用户存储（实际项目中应该使用数据库）
users = {}

# 登录视图
@bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        # 验证用户是否存在且密码正确
        if username in users and users[username] == password:
            flash('登录成功!', 'success')
            return redirect(url_for('blog.index'))
        else:
            flash('登录失败，请检查用户名和密码', 'danger')

    return render_template('auth/login.html', title='登录')

# 注册视图
@bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        confirm_password = request.form['confirm_password']

        # 验证输入
        if not username or not password:
            flash('用户名和密码不能为空', 'danger')
        elif password != confirm_password:
            flash('两次输入的密码不一致', 'danger')
        elif username in users:
            flash('用户名已存在', 'danger')
        else:
            # 注册成功，保存用户信息
            users[username] = password
            flash('注册成功，请登录', 'success')
            return redirect(url_for('auth.login'))

    return render_template('auth/register.html', title='注册')